package com.qianfeng.smartdevices.service.impl;


//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼            BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.smartdevices.cache.AreasCache;
import com.qianfeng.smartdevices.dto.ResultCode;
import com.qianfeng.smartdevices.event.UpdateAreaCacheEvent;
import com.qianfeng.smartdevices.exceptions.AddErrorException;
import com.qianfeng.smartdevices.exceptions.DeleteErrorException;
import com.qianfeng.smartdevices.exceptions.MybaseException;
import com.qianfeng.smartdevices.exceptions.UpdateErrorException;
import com.qianfeng.smartdevices.mapper.AreaMapper;
import com.qianfeng.smartdevices.pojo.Areas;
import com.qianfeng.smartdevices.pojo.CheckStatus;
import com.qianfeng.smartdevices.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by jackiechan on 2021/10/12 14:49
 *
 * @author jackiechan
 * @version 1.0
 * @since 1.0
 */
@Service
@Transactional
public class AreaServiceImpl implements AreaService {

    private AreaMapper areaMapper;


    @Autowired
    public void setAreaMapper(AreaMapper areaMapper) {
        this.areaMapper = areaMapper;
    }


    private AreasCache areasCache;


//    private UpdateAreaCacheEvent updateAreaCacheEvent;
//
//    @Autowired
//    public void setUpdateAreaCacheEvent(UpdateAreaCacheEvent updateAreaCacheEvent) {
//        this.updateAreaCacheEvent = updateAreaCacheEvent;
//    }


    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setAreasCache(AreasCache areasCache) {
        this.areasCache = areasCache;
    }

    @Override
    public List<Areas> findParentAreaByStatus(Long stauts) {
        List<Areas> areasList = areasCache.getAllData();
        //return areaMapper.findParentAreaByStatus(stauts);
        List<Areas> list = areasList.stream().filter(areas -> {

            return areas.getParentid() == null && (ObjectUtils.isEmpty(stauts)||areas.getStatus().equals(stauts));
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public void addArea(Areas areas) throws Exception {
        if (areas.isNull(CheckStatus.ADD)) {
            throw new AddErrorException("添加的数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        areaMapper.addArea(areas);
        //需要更新缓存
        //areasCache.init();
        context.publishEvent(new UpdateAreaCacheEvent());//发布事件
    }

    @Override
    public PageInfo<Areas> findAllAreasByNameLikeAndStatusEquals(int page, int limit, String areaname, Long status) {
        PageHelper.startPage(page, limit);
        //   List<Areas> areasList = areaMapper.findAllAreasByNameLikeAndStatusEquals(areaname, status);
        List<Areas> areasList = areasCache.getAllData();//从缓存中获取数据
        //缓存中的数据是没有分页加上过滤条件的
        //计算分页
        //从总数据中裁剪对应长度的数据,这样裁剪会产生越界的问题,在长度不满足需要的数据量的时候会出现越界
//        List<Areas> dataList = new ArrayList<>();
//        for (Areas areas : areasList) {
//            if (!ObjectUtils.isEmpty(areaname)) {
//                if (areas.getAreaname().contains(areaname)) {
//                    if (!ObjectUtils.isEmpty(status)) {
//                        if (areas.getStatus().equals(status)) {
//                            dataList.add(areas);
//                        }
//                    } else {
//                        dataList.add(areas);
//                    }
//                }
//            }
//        }
        //List<Areas> subList = areasList.subList((page - 1) * limit, page * limit);
//        List<Areas> subList = null;
//        if (areasList.size() > (page - 1) * limit) {
//            int end = 0;
//            if (areasList.size() >= page * limit) {
//                end = page * limit;
//            } else {
//                end = areasList.size();
//            }
//            subList = areasList.subList((page - 1) * limit,end);
//        }
        //获取到了符合条件的所有的数据
        List<Areas> subList = areasList.stream().filter(areas -> {
           // boolean b1 = ObjectUtils.isEmpty(areaname) && ObjectUtils.isEmpty(status);
            boolean b2= ObjectUtils.isEmpty(areaname)?true:areas.getAreaname().contains(areaname);
            boolean b3 = (ObjectUtils.isEmpty(status)||status==-100)? true : areas.getStatus().equals(status);
            return  b2 && b3;
        }).collect(Collectors.toList());
        //对数据进行分割
        List<Areas> list = subList.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
        PageInfo<Areas> pageInfo = new PageInfo<>(list);
        pageInfo.setTotal(subList.size());//设置的长度是符合条件的数据的长度

        return pageInfo;
    }

    @Override
    public Areas getAreaById(Long id) {
        //我们本身就存放了所有数据的缓存,没有必要查询数据库,可以从缓存中查询
//        List<Areas> areasList = areasCache.getAllAreas();
//        //遍历缓存
//        List<Areas> list = areasList.stream().filter(areas -> areas.getId() == id).collect(Collectors.toList());
//        //我们查询数据库主键是有索引的,效率非常高
//
//        return list.size() == 0 ? null : list.get(0);
        return areasCache.get(id);
    }

    @Override
    public void updateArea(Areas area) {
        if (area == null || area.isNull(CheckStatus.UPDATE)) {
            throw new AddErrorException("数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        if (0==area.getStatus()) {//如果也要更新状态为禁用
            List<Areas> areaList = getAreaByParentId(area.getId());//获取以当前区域 id 为父 id 的区域,如果有则不允许更新为禁用
            if (areaList.size() != 0) {
                throw new UpdateErrorException("当前区域的子区域不为空,无法禁用", ResultCode.DATA_NOT_ALLOW_NUL);
            }
        }

        try {
            areaMapper.updateArea(area);
            context.publishEvent(new UpdateAreaCacheEvent());//更新缓存
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpdateErrorException("更新失败", ResultCode.ERROR);

        }
    }

    @Override
    public void deleteAreas(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            throw new DeleteErrorException("没有传递 id", ResultCode.DATA_NOT_ALLOW_NUL);
        }

        try {
            areaMapper.deleteAreas(ids);
            context.publishEvent(new UpdateAreaCacheEvent());//更新缓存
        } catch (Exception e) {
            e.printStackTrace();
            throw new DeleteErrorException("删除失败", ResultCode.ERROR);
        }
    }
    @Override
    public List<Areas> getAreaByParentId(Long id) {
        if (id == null || id == 0) {
            throw new MybaseException("没有传递 id", ResultCode.DATA_NOT_ALLOW_NUL);
        }

        try {
            // List<Area> areaList = areaMapper.getAreaByParentId(id);
            List<Areas> allData = areasCache.getAllData();//从缓存查询所有数据
            List<Areas> areaList = allData.stream().filter(area -> id == area.getParentid()).collect(Collectors.toList());//获取父id和当前id一样的数据
            return areaList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MybaseException("查询失败", ResultCode.ERROR);

        }
    }

    @Override
    public List<Areas> findParentAreaByStatuslong(long stauts) {
        return findParentAreaByStatus(stauts);
    }

}
